package com.liangzong.betspider.utils;

import com.liangzong.betspider.config.ChromeDriverConfig;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.GeckoDriverService;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;

import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import static com.liangzong.betspider.utils.ProcessDataUtil.pause;
import static com.liangzong.betspider.utils.SpiderInfoUtil.threads;

@Slf4j
public class DriverUtil {


    public static WebDriver getChromeDriver(ChromeDriverConfig chromeDriverConfig, int port) {

        System.setProperty("webdriver.chrome.driver", chromeDriverConfig.getChromeDriverPath());
        ChromeOptions options = new ChromeOptions();
        LoggingPreferences loggingprefs = new LoggingPreferences();
        loggingprefs.enable(LogType.PERFORMANCE, Level.ALL);
        options.setCapability(CapabilityType.LOGGING_PREFS, loggingprefs);

        options.setExperimentalOption("excludeSwitches", Arrays.asList("enable-automation"));
        options.setExperimentalOption("useAutomationExtension", false);
        List<String> arguments = chromeDriverConfig.getArguments();
        for (String argument : arguments) {
            options.addArguments(argument);
        }
        //是否开启代理
        if (chromeDriverConfig.isEnable()) {
            String proxyServer = chromeDriverConfig.getServer();
            Proxy proxy = new Proxy().setHttpProxy(proxyServer).setSslProxy(proxyServer);
            options.setProxy(proxy);
        }
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(new ChromeDriverService.Builder().usingPort(port).build(), options);

        Map<String, Object> addScriptToEvaluateOnNewDocumentMap = new HashMap<>();
        addScriptToEvaluateOnNewDocumentMap.put("source", "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})");
        driver.executeCdpCommand("Page.addScriptToEvaluateOnNewDocument", addScriptToEvaluateOnNewDocumentMap);
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
        driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
        driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(30));


        return driver;
    }

    public static String open(int port) {
        String debugAddr = "-remote-debugging-port=" + port;
        String cmd = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe " + debugAddr + " --user-data-dir=\"%temp%\\\\" + port + "\" --remote-allow-origins=* --start-maximized  https://www.365365304.com/#/IP/B1";
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(cmd);
        } catch (Exception e) {
            System.out.println("Error!");
        }
        return "127.0.0.1:"+port;
    }

    public static WebDriver getChromeDriverRemote(ChromeDriverConfig chromeDriverConfig, int port) {
        String debugAddr = open(port);
        try {
            Thread.sleep(10*1000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.setProperty("webdriver.chrome.driver", chromeDriverConfig.getChromeDriverPath());
        ChromeOptions options = new ChromeOptions();
        LoggingPreferences loggingprefs = new LoggingPreferences();
        loggingprefs.enable(LogType.PERFORMANCE, Level.ALL);
        options.setCapability(CapabilityType.LOGGING_PREFS, loggingprefs);
        options.setExperimentalOption("debuggerAddress", debugAddr);
        ChromeDriver driver = new ChromeDriver(options);

        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
        driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
        driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(30));


        return driver;
    }

    public static WebDriver getFirefoxDriver(ChromeDriverConfig chromeDriverConfig, int port) {

        System.setProperty("webdriver.gecko.driver", chromeDriverConfig.getFirefoxDriverPath());
        FirefoxOptions options = new FirefoxOptions();
        //ff 不支持 使用这种可能可以  System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE, "FFLogs.txt");
        LoggingPreferences loggingprefs = new LoggingPreferences();
        loggingprefs.enable(LogType.PERFORMANCE, Level.ALL);
        options.setCapability(CapabilityType.LOGGING_PREFS, loggingprefs);

        List<String> arguments = chromeDriverConfig.getArguments();
        for (String argument : arguments) {
            options.addArguments(argument);
        }
        //是否开启代理
        if (chromeDriverConfig.isEnable()) {
            String proxyServer = chromeDriverConfig.getServer();
            Proxy proxy = new Proxy().setHttpProxy(proxyServer).setSslProxy(proxyServer);
            options.setProxy(proxy);
        }
        FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference("dom.webdriver.enabled", false);
        options.setProfile(profile);

        FirefoxDriver driver = new FirefoxDriver(new GeckoDriverService.Builder().usingPort(port).build(), options);

        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
        driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
        driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(30));

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("close driver");
            driver.close();
        }));
        return driver;
    }

    public static void gotoMatchListPage(WebDriver driver, boolean firstTime) {
        boolean clicked = false;
        int i = 0;
        while (!clicked) {
            i++;
            try {
                String pageSource = driver.getPageSource();
                try {
                    if (pageSource.indexOf("iip-IntroductoryPopup_Cross") != -1) {
                        WebElement tipElement = driver.findElement(By.cssSelector("div[class='iip-IntroductoryPopup_Cross']"));
                        tipElement.click();
                        pause();
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                try {

                    if (pageSource.indexOf("ccm-CookieConsentPopup_Accept") != -1) {
                        WebElement accept_cookie = driver.findElement(By.cssSelector("div[class='ccm-CookieConsentPopup_Accept ']"));
                        accept_cookie.click();
                        pause();
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                //跳转到详细页面
                List<WebElement> elements = driver.findElements(By.cssSelector("div[class^='ovm-Competition ovm-Competition-open ']"));
                WebElement webElement = elements.get(0);
                pause();
                WebElement element = webElement.findElement(By.cssSelector("div[class^='ovm-FixtureDetailsTwoWay_Wrapper']"));
                element.click();
                String currentUrl = driver.getCurrentUrl();
                if (currentUrl.indexOf("IP/EV") != -1) {
                    log.info("校验通过");
                    clicked = true;
                } else {
                    pause();
                }
            } catch (Exception e) {
                log.error("gotoMatchListPage 方法失败");
                if(i >= 5) {
                    break;
                }
                pause();
            }

        }
    }

}
